// 权限路由守卫
import { resetRouter } from '../index'
import { getToken } from '@/utils/auth'
import store from '@/store'
import NProgress from 'nprogress'

export default function (router) {
    NProgress.configure({ showSpinner: false }) // NProgress Configuration

    const whiteList = ['/login', '/404'] // no redirect whitelist

    router.beforeEach(async (to, from, next) => {
        NProgress.start() // start progress bar
        const hasToken = getToken()
        console.log('hasToken', hasToken)

        if (hasToken) {
            console.log('topath', to.path)

            if (to.path === '/login') {
                // next({ path: '/dashboard' })
                NProgress.done()
            } else {
                // const hasRoles = store.getters.roles && store.getters.roles.length > 0
                // if (hasRoles) {
                //     next()
                // } else {
                //     try {
                //         // 获取用户信息(角色)
                //         const { roles } = await store.dispatch('user/getInfo')
                //         // 基于角色生成动态路由
                //         const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
                //         // 重置并添加新路由
                //         resetRouter()
                //         router.addRoutes(accessRoutes)
                //         next({ ...to, replace: true }) // 确保addRoutes完成
                //     } catch (error) {
                //         // 删除token并转到登录页面重新登录
                //         await store.dispatch('user/resetToken')
                //         next(`/login?redirect=${to.path}`)
                //         NProgress.done()
                //     }
                // }
            }
        } else {
            if (whiteList.indexOf(to.path) !== -1) {
                next()
            } else {
                next(`/login`) // 否则全部重定向到登录页
                NProgress.done()
            }
        }
    })

    router.afterEach(() => {
        NProgress.done() // finish progress bar
    })
}
